#include "frameop.h"

frameOp::frameOp()
{

}

frameOp::~frameOp()
{
	//release frame
	cvReleaseImage(&bFrame);
}

int frameOp::init(CvSize size)
{
	//initialize frame
	bFrame = cvCreateImage (size,IPL_DEPTH_8U,1);
	cvSet(bFrame,cvScalar(0));
	
	fIndex = 0;
	
}
int frameOp::srcFrame(IplImage * frame)
{
	for (int i = 0; i < frame->height * frame->width * frame->nChannels; i++)
	{
		bFrame->imageData[i] = frame->imageData[i];
	}
}
int frameOp::updateBackground(IplImage * cFrame)
{
	int i;
	double bg;
	UCHAR b, c;
	for (i = 0; i < cFrame->height * cFrame->width * cFrame->nChannels; i++)
	{
		
		b = bFrame->imageData[i];
		c = cFrame->imageData[i];
			
		//bg = ((double)(cFrame->imageData[i] + (double)(bFrame->imageData[i] * C_BG_WEIGHT))/(double)(C_BG_WEIGHT + 1));
		bg =  ((double)( c + ( C_BG_WEIGHT * (b ) )) / ((double)( C_BG_WEIGHT + 1 ) ));
		if ( bg < 1.0)
		{
			// if background is close to the desired value, use approximate median
			if (bFrame->imageData[i] > cFrame->imageData[i])
			{
				bFrame->imageData[i] = (bFrame->imageData[i] < WHITE) ? bFrame->imageData[i] + 1 : WHITE;
			}
			else if (bFrame->imageData[i] < cFrame->imageData[i])
			{
				bFrame->imageData[i] = (bFrame->imageData[i] > 1) ? bFrame->imageData[i] - 1 : BLACK;
			}
			else
			{
				bFrame->imageData[i] = bFrame->imageData[i];
			}
		}
		else
		{
			bFrame->imageData[i] = bg;
		}
		
	}
	
	return 0;
}

int frameOp::subtractFrame(IplImage * cFrame)
{
	for (int i = 0; i < cFrame->height * cFrame->width * cFrame->nChannels; i++)
	{
		cFrame->imageData[i] = abs(cFrame->imageData[i] - bFrame->imageData[i]);
	}
	
	return 0;
}

int frameOp::thresholdFrame(IplImage * cFrame, int threshold)
{
	for (int i = 0; i < cFrame->height * cFrame->width * cFrame->nChannels; i++)
	{
		if (cFrame->imageData[i] <= threshold)
		{
			cFrame->imageData[i] = 0;
		}
		else
		{
			cFrame->imageData[i] = 255;
		}
	}
	
	return 0;
}

